using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OpenWaves.Web;

namespace OpenWaves.ImageTransformations.Web
{
    public sealed class WebImageTransformationModule : IHttpModule
    {
        private static readonly IEnumerable<string> ValidImageExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };

        public void Init(HttpApplication context)
        {
            context.PostAuthorizeRequest += this.context_PostAuthorizeRequest;
        }

        private void context_PostAuthorizeRequest(object sender, EventArgs e)
        {
            var application = (HttpApplication) sender;

            var url = application.Context.Request.GetRawRelativeUrl();

            if (ValidImageExtensions.Contains(url.Path.GetFileExtension(), StringComparer.OrdinalIgnoreCase) == false)
                return;

            var implementation = ServiceLocator.ResolveOptional<IWebImageTransformationModuleImplementation>();
            if (implementation != null)
                implementation.PostAuthorizeRequest(new HttpContextWrapper(application.Context));
        }

        public void Dispose()
        {
        }
    }
}